package com.aos.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtils
 * @Description:Redis工具类
 * @Author wumingwang
 * @Date 2018/9/11 10:16
 * @Version 1.0
 */
@Component
@Slf4j
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 写入缓存,默认保存12小时
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,12,TimeUnit.HOURS);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存对象错误！",e);
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value,expireTime,timeUnit);
//            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存对象错误！",e);
        }
        return result;
    }

    /**
     * 设置缓存有效期
     * @param key
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean setExpireTime(final String key,Long expireTime ,TimeUnit timeUnit) {
        boolean result = false;
        try {
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            log.error("Redis设置有效期错误！key:{}",key,e);
        }
        return result;
    }

    /**
     * 批量删除对应的value
     * @param keys
     */
    public boolean remove(final String... keys) {
        boolean result = false;
        int i = 0;
        for (String key : keys) {
            if(!remove(key)){
                i++;
            };
        }
        if(i == 0){
            result = true;
        }
        return result;
    }

    /**
     * 批量删除,key与pattern模糊匹配
     * @param pattern
     */
    public boolean removePattern(final String pattern) {
        boolean result = false;
        try{
            Set<Serializable> keys = redisTemplate.keys(pattern);
            if (keys.size() > 0){
                redisTemplate.delete(keys);
            }
            result = true;
        }catch (Exception e){
            log.error("模糊匹配删除缓存错误！pattern:{}",pattern,e);
        }
        return result;
    }
    /**
     * 删除对应的value
     * @param key
     */
    public boolean remove(final String key) {
        boolean result = false;
        try{
            if (exists(key)) {
                redisTemplate.delete(key);
            }
            result = true;
        }catch (Exception e){
            log.error("删除缓存错误！key:{}",key,e);
        }
        return result;
    }
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        try{
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            result = operations.get(key);
        }catch (Exception e){
            log.error("获取缓存错误！key：{}",key,e);
        }
        return result;
    }

    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     */
    public boolean setHash(String key, Object hashKey, Object value){
        boolean result = false;
        try {
            HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
            hash.put(key,hashKey,value);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存哈希错误！",e);
        }
        return result;
    }

    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public Object getHash(String key, Object hashKey){
        Object result = null;
        try {
            HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
            result = hash.get(key,hashKey);
        } catch (Exception e) {
            log.error("Redis获取哈希错误！key:{}",key,e);
        }
        return result;
    }

    /**
     * 列表添加
     * @param key
     * @param list
     */
    public boolean setList(String key,List<?> list){
        boolean result = false;
        try {
            ListOperations<String, Object> listops = redisTemplate.opsForList();
            if (null != list) {
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    listops.rightPush(key, list.get(i));
                }
            }
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存List错误！",e);
        }
        return result;
    }

    /**
     * 列表添加
     * @param key
     * @param list
     */
    public boolean setList(String key,List<?> list,Long expireTime ,TimeUnit timeUnit){
        boolean result = false;
        try {
            ListOperations<String, Object> listops = redisTemplate.opsForList();
            if (null != list) {
                int size = list.size();
                for (int i = 0; i < size; i++) {
                    listops.rightPush(key, list.get(i));
                }
            }
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存List并设置时效错误！",e);
        }
        return result;
    }

    /**
     * 消费list(获取并删除)
     * @param key
     * @return
     */
    public List<?> consumeList(String key){
        List<?> result = null;
        try {
            ListOperations<String, Object> listops = redisTemplate.opsForList();
            if(listops.leftPop(key) != null){
                result =  (List<?>) listops.leftPop(key);
            }
        } catch (Exception e) {
            log.error("Redis获取List错误！key:{}",key,e);
        }
        return result;
    }

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<?> getList(String key,long start, long end){
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的内容
     * @param key 键
     * @return
     */
    public List<?> getList(String key){
        return getList(key,0,-1);
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public boolean addSet(String key,Set<?> set){
        boolean result = false;
        try {
            SetOperations<String, Object> setoper = redisTemplate.opsForSet();
            if(set != null && set.size() > 0){
                Iterator<?> it = set.iterator();
                while (it.hasNext()) {
                    setoper.add(key,it.next());
                }
            }
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存Set错误！",e);
        }
        return result;
    }

    /**
     * 集合添加
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean addSet(String key,Set<?> set,Long expireTime ,TimeUnit timeUnit){
        boolean result = false;
        try {
            SetOperations<String, Object> setoper = redisTemplate.opsForSet();
            if(set != null && set.size() > 0){
                Iterator<?> it = set.iterator();
                while (it.hasNext()) {
                    setoper.add(key,it.next());
                }
            }
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存Set并设置时效错误！",e);
        }
        return result;
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public Set<?> membersSet(String key){
        Set<?> result = null;
        try {
            SetOperations<String, Object> set = redisTemplate.opsForSet();
            result =  set.members(key);
        } catch (Exception e) {
            log.error("Redis获取Set错误！key:{}",key,e);
        }
        return result;
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public boolean zAdd(String key,Object value,double scoure){
        boolean result = false;
        try {
            ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
            zset.add(key,value,scoure);
            result = true;
        } catch (Exception e) {
            log.error("Redis缓存有序集合错误！",e);
        }
        return result;
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<?> rangeByScore(String key,double scoure,double scoure1){
        Set<?> result = null;
        try {
            ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
            result = zset.rangeByScore(key, scoure, scoure1);
        } catch (Exception e) {
            log.error("Redis获取有序集合错误！key:{}",key,e);
        }
        return result;
    }

    /**
     * 缓存字符串，默认有效期12小时
     * @param key
     * @param value
     * @return
     */
    public boolean setString(String key,String value){
        boolean flag = false;
        try{
            stringRedisTemplate.opsForValue().set(key, value,12,TimeUnit.HOURS);
            flag = true;
        }catch (Exception e){
            log.error("Redis缓存字符串错误！",e);
        }
        return flag;
    }

    /**
     * 设置有效期的缓存字符串
     * @param key
     * @param value
     * @param expireTime
     * @param timeUnit
     * @return
     */
    public boolean setString(String key,String value, Long expireTime ,TimeUnit timeUnit){
        boolean flag = false;
        try{
            stringRedisTemplate.opsForValue().set(key, value,expireTime,timeUnit);
            flag = true;
        }catch (Exception e){
            log.error("Redis缓存字符串错误！",e);
        }
        return flag;
    }

    /**
     * 获取缓存的字符串
     * @param key
     * @return
     */
    public String getString(String key){
        String result = null;
        try {
            result = stringRedisTemplate.boundValueOps(key).get();
        } catch (Exception e) {
            log.error("Redis获取字符串错误！key:{}",key,e);
        }
        return result;
    }
}
